<template>
  <div class="my-breadcrumb">
    <!-- {{ breadcrumbs }} -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item v-for="(item, index) in breadcrumbs" :key="index">
        <router-link v-if="index < breadcrumbs.length - 1" :to="item.path">
          {{ item.meta.title }}
        </router-link>
        <span v-else>{{ item.meta.title }}</span>
      </el-breadcrumb-item>
    </el-breadcrumb>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const breadcrumbs = ref([])

const getBreadcrumbs = () => {
  const matched = route.matched.filter(item => item.meta && item.meta.title)
  console.log(matched)
  // 处理首页
  const home = { path: '/', meta: { title: '首页' } }
  if (matched[0]?.path !== '/') {
    matched.unshift(home)
  }

  breadcrumbs.value = matched
}

// 初始调用
getBreadcrumbs()

// 监听路由变化
watch(() => route.path, getBreadcrumbs)
</script>

<style lang="scss" scoped>
.my-breadcrumb :deep(.el-breadcrumb) {
  line-height: 40px !important;
}
</style>